<template>
  <div class="negotiation-list-container">
    <el-card class="list-card">
      <template #header>
        <div class="card-header">
          <span>协商列表</span>
          <div class="header-actions">
            <el-input
              v-model="searchAdname"
              placeholder="输入广告名搜索"
              prefix-icon="Search"
              clearable
              @clear="handleSearchClear"
              @keyup.enter="handleSearch"
              style="width: 200px"
            ></el-input>
            <el-button type="primary" @click="handleSearch" style="margin-left: 10px">
              <el-icon><Search /></el-icon>搜索
            </el-button>
          </div>
        </div>
      </template>

      <el-table
        v-loading="loading"
        :data="negotiationList"
        stripe
        style="width: 100%"
      >
        <!-- 表格列定义保持不变 -->
        <el-table-column prop="deviceOwnerName" label="设备所有者" width="150"></el-table-column>
        <el-table-column prop="advertisementName" label="广告名称" width="200"></el-table-column>
        <el-table-column prop="price" label="协商价格" width="120">
          <template #default="scope">
            ¥{{ scope.row.price }}
          </template>
        </el-table-column>
        <el-table-column prop="timeSlots" label="播放时段" width="180">
          <template #default="scope">
            <div v-for="(slot, index) in scope.row.timeSlots" :key="index">
              {{ slot.startTime }} - {{ slot.endTime }}
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createdTime" label="创建时间" width="180">
          <template #default="scope">
            {{ formatDateTime(scope.row.createdTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="280" fixed="right">
          <template #default="scope">
            <el-button 
              type="primary" 
              size="small" 
              :icon="ChatDotRound"
              @click="goToChat(scope.row.id)"
            >
              聊天
            </el-button>
            <el-button 
              type="info" 
              size="small" 
              :icon="View"
              @click="viewDetail(scope.row.id)"
            >
              详情
            </el-button>
            <el-button 
              v-if="scope.row.status === 0"
              type="success" 
              size="small" 
              @click="completeNegotiation(scope.row.id)"
            >
              完成
            </el-button>
            <el-button 
              v-if="scope.row.status === 0"
              type="danger" 
              size="small" 
              @click="cancelNegotiation(scope.row.id)"
            >
              取消
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          background
          layout="total, prev, pager, next"
          :page-size="pageSize"
          :total="total"
          :current-page="currentPage"
          @current-change="handleCurrentChange"
        ></el-pagination>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Search, ChatDotRound, View } from '@element-plus/icons-vue';
import { getNegotiationList, completeNegotiation as completeNegotiationApi, 
  cancelNegotiation as cancelNegotiationApi } from '@/api/negotiation';

const router = useRouter();
const loading = ref(false);
const negotiationList = ref([]);
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
const searchAdname = ref('');

// 获取协商列表
const fetchNegotiationList = async () => {
  try {
    loading.value = true;
    const params = {
      pageNum: currentPage.value,
      pageSize: pageSize.value
    };
    
    // 只在有值时添加adname参数
    if (searchAdname.value && searchAdname.value.trim() !== '') {
      params.adname = searchAdname.value.trim();
    }
    
    console.log('请求参数:', params); // 调试用
    
    const res = await getNegotiationList(params);
    console.log('协商列表响应:', res);
    if (res.data.code === 200) {
      negotiationList.value = res.data.data.records;
      total.value = res.data.data.total;
    } else {
      ElMessage.error(res.data.message || '获取协商列表失败');
    }
  } catch (error) {
    console.error('获取协商列表失败', error);
    ElMessage.error('获取协商列表失败');
  } finally {
    loading.value = false;
  }
};

// 页码变化
const handleCurrentChange = (val) => {
  currentPage.value = val;
  fetchNegotiationList();
};

// 搜索清除
const handleSearchClear = () => {
  searchAdname.value = '';
  fetchNegotiationList();
};

// 搜索按钮点击
const handleSearch = () => {
  currentPage.value = 1; // 重置到第一页
  fetchNegotiationList();
};

// 获取状态类型
const getStatusType = (status) => {
  const statusMap = {
    0: 'warning',  // 进行中
    1: 'success',  // 已完成
    2: 'info'      // 已取消
  };
  return statusMap[status] || 'info';
};

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    0: '进行中',
    1: '已完成',
    2: '已取消'
  };
  return statusMap[status] || '未知';
};

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return '';
  const date = new Date(dateTime);
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
};

// 前往聊天
const goToChat = (negotiationId) => {
  router.push({
    path: `/advertiser/chat/${negotiationId}`
  });
};

// 查看详情
const viewDetail = (negotiationId) => {
  router.push({
    path: `/advertiser/negotiation/${negotiationId}`
  });
};

// 完成协商
const completeNegotiation = async (negotiationId) => {
  try {
    await ElMessageBox.confirm('确定要完成此协商吗？完成后将进入合约生成阶段。', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });
    
    const res = await completeNegotiationApi(negotiationId);
    if (res.data && res.data.code === 200) {
      ElMessage.success('协商已完成');
      fetchNegotiationList();
    } else {
      ElMessage.error((res.data && res.data.message) || '操作失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('完成协商失败', error);
      ElMessage.error('操作失败');
    }
  }
};

// 取消协商
const cancelNegotiation = async (negotiationId) => {
  try {
    await ElMessageBox.confirm('确定要取消此协商吗？取消后将不可恢复。', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });
    
    const res = await cancelNegotiationApi(negotiationId);
    if (res.data && res.data.code === 200) {
      ElMessage.success('协商已取消');
      fetchNegotiationList();
    } else {
      ElMessage.error((res.data && res.data.message) || '操作失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('取消协商失败', error);
      ElMessage.error('操作失败');
    }
  }
};

onMounted(() => {
  fetchNegotiationList();
});
</script>

<style scoped>
.negotiation-list-container {
  padding: 20px;
}

.list-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  align-items: center;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.el-table {
  margin-top: 20px;
}

.el-button {
  margin-right: 8px;
}

.el-button:last-child {
  margin-right: 0;
}

.el-tag {
  min-width: 60px;
  text-align: center;
}
</style>